#ifndef _GEN_VIDEO_SWF_HPP_
#define _GEN_VIDEO_SWF_HPP_

#include "video.hpp"
#include "gen_figure_swf.hpp"

class video_swf:public figure_swf {
	video* vid;
public:

	string capture_image(){
  		SWFMovie *movie=new SWFMovie;
		movie->setDimension(vid->slide_width,vid->slide_height);
  		SWFVideoStream *vidstream=new SWFVideoStream(vid->input_file.c_str());
		SWFDisplayItem *v=movie->add(vidstream);
		movie->nextFrame();
		string capname=vid->name+"-capture.swf";
  		movie->save(capname.c_str());
  		delete vidstream;
  		delete movie;
  		vid->garbage.push_back(capname);
  		return capname;
	}
	
	virtual string make_player() {
		char vs[128];
		
		vid->video_width=get_width();
		vid->video_height=get_height();
		
		cerr << "movie player: using script " << get_scriptpath("movie") << "\n";
		
		sprintf(vs,"var video_width=%d;\nvar video_height=%d;\n", 
		       (int)vid->video_width,(int)vid->video_height);
		
		string act("var movie_file_name='");
		act.append(vid->input_file+"';\n");
		act.append(vs);
		act.append(cat(get_scriptpath("movie")));

		Ming_useSWFVersion(6);
		SWFMovie* movie=new SWFMovie;

		movie->setDimension(vid->video_width,vid->video_height);		
		movie->setBackground(0,0,0);

		SWFPrebuiltClip *shot=new SWFPrebuiltClip(capture_image().c_str());
		SWFDisplayItem *btn=movie->add(shot);
		btn->setName("video_button");

		SWFVideoStream* vidstream=new SWFVideoStream();
		SWFDisplayItem* v=movie->add(vidstream);
		v->setName("video_clip");
		movie->add(new SWFAction(act.c_str()));
		movie->nextFrame();
		string playername=vid->name+"-player.swf";
		movie->save(playername.c_str());
		delete movie;
		vid->garbage.push_back(playername);
		assert(file_exist(playername), "failed in generating video player");
		return playername;
	}
	
	virtual double draw(void* draw_param){
		vid=dynamic_cast<video*>(it);
		SWFSprite *grp=(SWFSprite*)draw_param;

		cerr << "embedding movie: " << vid->input_file.c_str() << "\n";

		string vplayer=make_player();

		SWFPrebuiltClip *spc=new SWFPrebuiltClip(vplayer.c_str());
		SWFDisplayItem *di=grp->add(spc);
		di->scale(vid->scalex,vid->scaley);

		set_width(vid->scalex*vid->video_width);
		set_height(vid->scaley*vid->video_height+get_spacing());

		vid->pinning();

		// FIXME! this is ugly... pinning needed!
		set_offset(0.0,get_height());
		set_height(get_height()+text_swf::draw(grp));
		return get_height();
	}

};


#endif
